export default {
    name: "admin",
    setup(props) {
        const router = VueRouter.useRouter();
        const route = VueRouter.useRoute();
        const configs = inject('globalConfigs');
        const originalUser = ref({}); // 原始用户数据用于比较修改
        const user = ref({name: '',phone: '',email: '', new_password: '', old_password: ''});
        const token = ref(localStorage.getItem('token') || '');
        const dialoguser = ref(false);
        const userform = ref();
        // 新增消息相关状态
        const messages = ref([]);
        const unreadCount = ref(0);
        const totalMessages = ref(0);
        const pageSize = ref(10);
        const currentPage = ref(1);
        const messageVisible = ref(false);
        const menuItems = ref([]);
        
        onMounted(async() => {
            if (token.value) {
                const res = await getuser(); //从token获取用户信息
                if(!['admin', 'xmgly', 'tby'].includes(res.Role)) {
                    router.push({name: 'home'});
                    return
                }
                originalUser.value = res;
                localStorage.setItem('user', JSON.stringify(originalUser.value));
                user.value = {
                    username: res.Username || '',
					name: res.Name || '',
					phone: res.Phone || '',
					email: res.Email || '',
				}
                loadMessages();
            }else{
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                token.value = '';
                user.value = { name: '', phone: '', email: '' };
                originalUser.value = {};
                ElMessage.success("请先登录");
                router.push({name: 'login'});
            }
        });
        
        const checkMenuLoaded = () => {
            if (window.menus) {
                menuItems.value = window.menus;
                return true;
            }
            return false;
        };
        
        // 菜单是否折叠
        const isCollapse = ref(false);
        
        // 获取消息数据
        const loadMessages = async (page = 1) => {
            try {
                const res = await getmessages({
                    page: page,
                    pageSize: pageSize.value
                });
                messages.value = res.items;
                totalMessages.value = res.total;
                unreadCount.value = res.isnotread;
                currentPage.value = page;
            } catch (error) {
                console.error('获取消息失败:', error);
                ElMessage.error('获取消息失败');
            }
        };
        
        // 打开消息弹窗
        const showMessageBox = () => {
            messageVisible.value = true;
        };

        // 标记单条消息为已读
        const openMessage = async (msg) => {
            if (!msg.isRead) {
                await markmessageread({
                    messageId: msg.id
                });
                msg.isRead = true;
                unreadCount.value -= 1;
            }
        };

        // 标记全部已读
        const markAllAsRead = async () => {
            // 获取所有未读消息ID
            const unreadIds = messages.value.filter(msg => !msg.isRead).map(msg => msg.id);
            // 批量标记已读
            if (unreadIds.length > 0) {
                await Promise.all(unreadIds.map(id => markmessageread({ messageId: id })));
                // 更新本地状态
                messages.value.forEach(msg => {
                    if (unreadIds.includes(msg.id)) {
                        msg.isRead = true;
                    }
                });
                unreadCount.value -= unreadIds.length;
                ElMessage.success(`已标记${unreadIds.length}条消息为已读`);
            }
        };
        
    	//修改用户信息，debounce防抖
        const submitForm = _.debounce(async() => {
            try {
                const valid = await userform.value.validate();
                if (!valid) {
                    return;
                }
                if (!window.validators.isMobile(user.value.phone)) {
                    ElMessage.error('手机号错误');
                    return;
                }
                // 密码修改处理
				if (user.value.new_password && !window.validators.isPasswordSecure(user.value.new_password)) {
                    ElMessage.error('密码必须包含大小写字母、数字和特殊字符');
                    return;
				}
                user.value.phone = user.value.phone.toString(); // 转换手机号为字符串
                //提交前先校验是否有修改
                if(user.value.name == originalUser.value.Name && user.value.phone == originalUser.value.Phone && user.value.email == originalUser.value.Email) {
                    ElMessage.error('信息无变更');
                    return;
                }
                let res = await updateuserapi(user.value);
                ElMessage.success('修改成功');
                dialoguser.value = false; // 关闭对话框
                res = await getuser(); //从token获取用户信息
                originalUser.value = res;
                localStorage.setItem('user', JSON.stringify(originalUser.value));
                user.value = {
                    username: res.Username || '',
					name: res.Name || '',
					phone: res.Phone || '',
					email: res.Email || ''
				}
            } catch (error) {
                console.error('表单验证失败:', error);
                ElMessage.error('表单验证失败，请检查输入');
            }
        }, 300);
        
        // 面包屑动态生成
        const breadcrumbs = computed(() => {
    		const matched = route.matched.filter(r => r.meta?.title);
    		return matched.map(r => ({
    			path: r.path,
    			title: r.meta.title
    		}));
    	});

        // 退出登录
        const handleLogout = () => {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            token.value = '';
            user.value = { name: '', phone: '', email: '' };
            originalUser.value = {};
            ElMessage.success("退出成功");
            setTimeout(() => {
                router.push({ name: 'home' });
            }, 1000);
        }
        
        //返回首页
        const goHome = () => {
            router.push({ name: 'home' });
        }
        
        return {
            configs,
            goHome,
            isCollapse,
            handleLogout,
            breadcrumbs,
            imgurl: window.APP_CONFIG.staticBase + '/tx.jpg',
            dialoguser,
            user,
            userform,
            originalUser,
            submitForm,
            roles: {user: '普通', tby: '填报员', xmgly: '项目管理员', admin: '管理员'},
            messages,
            unreadCount,
            totalMessages,
            messageVisible,
            showMessageBox,
            openMessage,
            markAllAsRead,
            loadMessages,
            pageSize,
            menuItems,
            checkMenuLoaded,
        };
  },
  
    template: `
	<el-container class="admin-container">
        <el-dialog v-model="dialoguser" title="修改个人信息" style="padding:30px">
            <el-form :model="user" ref="userform" label-position="top">
                <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入姓名' }]">
                	<el-input v-model="user.name" placeholder="输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" :rules="[{ required: true, message: '请输入手机号'}]">
                    <el-input v-model="user.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email":rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
                    <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="当前积分">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <el-input-number v-model="originalUser.Points" :min="0" disabled style="flex: 1;"></el-input-number>
                    </div>
                </el-form-item>
                <el-form-item label="新密码" prop="new_password">
                	<el-input type="password" v-model="user.new_password" placeholder="输入新密码"></el-input>
                	<p style="margin-top:-5px;">如果密码不需要修改，此项请留空。</p>
                </el-form-item>
                <el-form-item label="旧密码" prop="old_password">
                	<el-input type="password" v-model="user.old_password" placeholder="输入旧密码"></el-input>
                	<p style="margin-top:-5px;">修改密码必须输入旧密码。</p>
                </el-form-item>
                <el-row justify="center">
                	<el-col :span="8" style="text-align: center;margin: 20px;">
                		<el-button type="primary" @click="submitForm">提交保存</el-button>
                	</el-col>
                </el-row>
            </el-form>
        </el-dialog>
	
		<!-- 侧边栏 -->
		<el-aside :width="isCollapse ? '64px' : '200px'" class="aside-menu">
			<div class="logo-area">
                <el-icon :size="20" class="logo"><HomeFilled /></el-icon>
				<span v-if="!isCollapse"><b>后台管理系统</b></span>
			</div>

			<el-menu :default-active="$route.path" :collapse="isCollapse" :collapse-transition="false" router
				class="vertical-menu">
				<template v-if="checkMenuLoaded()" v-for="item in menuItems" :key="item.path">
				    <template v-if="item.visible && item.roles.includes(originalUser.Role)">
                        <el-sub-menu v-if="item.children.length > 0" :index="item.fullPath">
                        	<template #title>
                        		<el-icon>
                        			<component :is="item.icon" />
                        		</el-icon>
                        		<span>{{ item.name }}</span>
                        	</template>
                        	<el-menu-item v-for="child in item.children" :key="child.path" :index="child.fullPath">
                        		{{ child.name }}
                        	</el-menu-item>
                        </el-sub-menu>
                        
                        <el-menu-item v-else :index="item.fullPath">
                        	<el-icon>
                        		<component :is="item.icon" />
                        	</el-icon>
                        	<template #title>{{ item.name }}</template>
                        </el-menu-item>
    				</template>
				</template>
				<el-skeleton v-else :rows="5" animated />
			</el-menu>
		</el-aside>

		<el-container>
			<!-- 顶部导航 -->
			<el-header class="main-header">
				<div class="header-left">
					<el-button @click="isCollapse = !isCollapse" :icon="isCollapse ? 'Expand' : 'Fold'"
						circle />
					<div class="breadcrumb">
						<el-breadcrumb separator="/">
                    		<el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index"
                    			:to="index < breadcrumbs.length - 1 ? item.path : undefined">
                    			{{ item.title }}
                    		</el-breadcrumb-item>
                    	</el-breadcrumb>
					</div>
				</div>

				<div class="header-right">
                    <!-- 新增消息提醒 -->
                    <div class="message-notice">
                        <el-badge :value="unreadCount" :max="99" :hidden="unreadCount === 0" type="danger" @click="showMessageBox">
                            <el-icon :size="20" class="notice-icon"><Bell /></el-icon>
                        </el-badge>
                        
                        <!-- 消息弹窗 -->
                        <el-popover v-model="messageVisible" placement="bottom-end" trigger="click" :width="380" popper-class="message-popover">
                            <template #reference>
                                <div class="message-trigger"></div>
                            </template>
                            
                            <div class="message-box">
                                <div class="message-header">
                                    <span>我的消息</span>
                                    <el-button type="text" @click="markAllAsRead" :disabled="unreadCount === 0">全部标记已读</el-button>
                                </div>
                                
                                <el-scrollbar height="500px">
                                    <div v-for="msg in messages" :key="msg.id" class="message-item" :class="{ unread: !msg.isRead }" @click="openMessage(msg)">
                                        <div class="message-content">
                                            <div class="message-title">
                                                {{ msg.title }}
                                                <el-tag v-if="!msg.isRead" size="small" type="danger">未读</el-tag>
                                            </div>
                                            <div class="message-time">{{ $validators.formatDate(msg.createdAt) }}</div>
                                        </div>
                                        <div class="message-body">{{ msg.content }}</div>
                                    </div>
                                    
                                    <div v-if="messages.length === 0" class="empty-message">暂无消息</div>
                                </el-scrollbar>
                                
                                <div class="message-footer">
                                    <el-pagination small layout="prev, pager, next" :total="totalMessages" :page-size="pageSize" @current-change="loadMessages"/>
                                </div>
                            </div>
                        </el-popover>
                    </div>
					<el-dropdown>
						<span class="user-info">
							<el-avatar :src="imgurl" />
							<span>{{originalUser.Name || '匿名'}}</span> - 
							<span>{{originalUser.Role ? roles[originalUser.Role] : '普通'}}</span>
						</span>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item @click="goHome">返回首页</el-dropdown-item>
								<el-dropdown-item @click="dialoguser = true">修改账户</el-dropdown-item>
								<el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>
			</el-header>

			<!-- 主内容区域 -->
            <el-main class="main-content">
                <router-view></router-view>
            </el-main>
		</el-container>
	</el-container>
    `,
};